package baiqi.sishen.community.provider;

import baiqi.sishen.community.dto.AccessTokenDto;
import baiqi.sishen.community.provider.model.GiteeUser;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONCreator;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Component;

/**
 * @author 兕神
 * @version 1.0
 * DateTime: 2023/4/26
 */
@Component
@Slf4j
public class GiteeProvider {
    /**
     *用于实现发post请求到gitee获取accessToken
     * @param accessTokenDto 请求的组装dto
     * @return accessTokenDto
     */
    public String accessToken(AccessTokenDto accessTokenDto) {
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();

        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(accessTokenDto));
        String url = "https://gitee.com/oauth/token?grant_type=authorization_code&code=%s&client_id=%s&redirect_uri=%s&client_secret=%s";
        url = String.format(url, accessTokenDto.getCode(), accessTokenDto.getClient_id(), accessTokenDto.getRedirect_uri(), accessTokenDto.getClient_secret());
        //发送请求
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        //获取请求回复
        try (Response response = client.newCall(request).execute()) {
            //获取请求体
            String string = response.body().string();
            //转换为JSON对象
            JSONObject jsonObject = JSON.parseObject(string);
            return jsonObject.getString("access_token");
        } catch (Exception e) {
            log.error("getAccessToken error,{}", accessTokenDto, e);
        }
        return null;
    }

    /**
     *用于实现根据accessToken授权获取用户信息
     * @param accessToken 授权码
     * @return GiteeUser
     */
    public GiteeUser getGiteeUser(String accessToken) {
        OkHttpClient client = new OkHttpClient();
        //发送请求用户信息请求
        Request request = new Request.Builder()
                .url("https://gitee.com/api/v5/user?access_token=" + accessToken)
                .build();
        try {
            //获取请求回复
            Response response = client.newCall(request).execute();
            String giteeUserJSON = response.body().string();
            GiteeUser giteeUser = JSON.parseObject(giteeUserJSON, GiteeUser.class);
            return giteeUser;
        } catch (Exception e) {
            log.error("getUser error,{}", accessToken, e);
        }
        return null;
    }
}
